
import EventManager from "../../Common/EventManager";
import GlobalPool from "../../Common/GlobalPool";
import http_request from "../../Common/http_request";
import Loader from "../../Common/Loader";
import yyComponent from "../../Common/yyComponent";
import InfinityPowerPage from "../../frameSccript/other/page/infinityPowerPage";
import UIService from "../../frameSccript/services/uiService";
import UserService from "../../frameSccript/services/userService";
import { mgrs, sers } from "../../frameSccript/system/OverallSystem ";
import { EventType } from "../../GameSpecial/GameEventType";
import gameItem from "./gameItem";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NormalMode extends yyComponent {

    // onLoad () {}

    @property(cc.PageView)
    pageView: cc.PageView = null

    @property(cc.Node)
    page: cc.Node = null

    @property(cc.Node)
    item: cc.Node = null

    @property(cc.Prefab)
    item2:cc.Prefab = null


    @property(cc.Label)
    yeshu: cc.Label = null

    @property(cc.Button)
    shang: cc.Button = null
    @property(cc.Button)
    xia: cc.Button = null


    @property(cc.Node)
    jiesuoNode: cc.Node = null

    @property(cc.Node)
    tianjiazhuomianBtn: cc.Node = null

    @property(cc.Node)
    yinsiBtn: cc.Node = null

    @property(cc.Node)
    moreGameBtn: cc.Node = null

    private url = "https://changshazhise01-1254961065.cos.ap-guangzhou.myqcloud.com/cp/tt_wzwz/guanqia/guanqia.json"
    start() {
        this.node.getComponent(cc.Canvas).fitHeight = UserService.IPAD
        this.node.getComponent(cc.Canvas).fitWidth = !UserService.IPAD

        // http_request.getInstance().get(this.url, null, this.yuancheng.bind(this));


        // if((cc.sys.platform == cc.sys.BYTEDANCE_GAME||cc.sys.platform == cc.sys.BYTEDANCE_GAME_SUB) && window['tt']){
        //     zs_sdk.zs_network.config(false,'configLevel').then((res)=>{
        //         let item = res.configLevel[0].config_item
        //         item = item.replace(/\s+/g,'')
        //         if(item && JSON.parse(item)){
        //             this.saveJson(JSON.parse(item))
        //             cc.log('开关配置数据2')
        //         }else{
        //             this.bendi()
        //         }
        //     })
        //     // zs_sdk.zs_network.config(true).then((res)=>{
        //     //     cc.log(res)
        //     //     cc.log('开关配置数据')
        //     // })
        // }else{
        //     this.bendi()
        // }
        this.bendi()


        this.on(EventType.DirectorEvent.lockLevel, this.lockLevel, this)
        this.on(EventType.DirectorEvent.showCheck, this.showCheck, this)
        this.showCheck()
        // this.tianjiazhuomianBtn.active = false
    }

    private bendi(){
        Loader.loadBundleRes('NormalMode', 'json/guanqia' + sers().userSrv.getGameList(), (res) => {
            cc.log('本地')
            cc.log(res.json)
            // cc.log(JSON.stringify(res.json))
            if(!this || !this.node)return
            this.saveJson(res.json)
        })
    }

    saveJson(json){

        let showdata = [
            // {
            //     gameId:35,
            //     level:1,
            //     time:Date.parse("4-30-2023 18:00:00")
            // },
            // {
            //     gameId:36,
            //     level:1,
            //     time:Date.parse("4-20-2023 18:00:00")
            // }
        ]

        // if(UserService.daren){
        //     showdata = [
        //          {
        //             gameId:35,
        //             level:1,
        //             time:Date.parse("4/30/2023 10:00:00")
        //         },
        //         {
        //             gameId:36,
        //             level:1,
        //             time:Date.parse("5/2/2023 10:00:00")
        //         }
        //     ]
        // }else{
        //     showdata = [
        //     //     {
        //     //        gameId:35,
        //     //        level:1,
        //     //        time:Date.parse("4/30/2023 18:00:00")
        //     //    },
        //     //    {
        //     //        gameId:36,
        //     //        level:1,
        //     //        time:Date.parse("5/2/2023 18:00:00")
        //     //    }
        //    ]
        // }

        let d =  new Date().getTime()
        
        let newjson = []
        for (const iterator of json) {
            let f = true
            for (const iterator2 of showdata) {
                if(iterator.gameId == iterator2.gameId && iterator.level == iterator2.level){
                    if(d<iterator2.time){
                        f = false
                    }
                }
            }
            if(f){
                newjson.push(iterator)
            }
        }

     
        json  = newjson

        if(UserService.zs_level_switch){
            json = UserService.zs_level_switch
        }

        UserService.maxLevel =json.length
        UserService.guanqia = json

        console.log(json)
        let page = this.page
       
        for (let i = 0; i < json.length; i++) {
            const element = json[i];
            let item = this.item

           
            if (i > 0) {
                item = cc.instantiate(this.item)
            }
            
            if(UserService.guanqia[i].gameId >= 68){
                let itemparent =item.getComponent(gameItem).parentNode
                item = cc.instantiate(this.item2)
                item.getComponent(gameItem).parentNode =itemparent
                if(i == 0){
                this.item.active = false

               }
            }

            item.getComponent(gameItem).LevelId = element.level
            item.getComponent(gameItem).bao = element.bao
            item.children[0].getComponent(cc.Label).string = element.title
            item.getComponent(gameItem).gameId = element.gameId
            item.getComponent(gameItem).Id_ = i
            item.getComponent(gameItem).data = element
            item.getComponent(gameItem).title = element.title
            item.active = true
            
            if(element.unlockNumber){
                item.getComponent(gameItem).unlockNumber = element.unlockNumber
            }


            if (i % 6 == 0 && i != 0) {
                page = cc.instantiate(this.page)
                page.removeAllChildren()
                this.pageView.addPage(page)
            }
            item.parent = page
            item.getComponent(gameItem).updateView()
        }
        this.updatav()
        if (this.pageView.getPages().length < 2) {
            this.shang.node.active = false
            this.xia.node.active = false
            this.yeshu.node.active = false
        } else {
            this.shang.node.active = true
            this.xia.node.active = true
            this.yeshu.node.active = true
        }
    }

    yuancheng(data){
        cc.log('远程')
        cc.log(data)
        this.saveJson(data)
    }
    showCheck(){
        
        if (window['tt'] && window['tt'].checkShortcut) {
            let that = this
            window['tt'].checkShortcut({
                success(res) {
                    cc.log("检查快捷方式", res.status);
                    that.tianjiazhuomianBtn.active = !res.status.exist
                    window['tt'].getSystemInfo({
                        success(res) {
                            cc.log('appName:'+res.appName);
                            if (res.appName == "Tt_lite" || res.appName == "Toutiao" || res.appName == "xigua") {
                                that.tianjiazhuomianBtn.active = false;
                            }
                        },
                        fail(res) {
                            cc.log(`getSystemInfo 调用失败`);
                        },
                    });

                },
                fail(res) {
                    cc.log("检查快捷方式失败", res.errMsg);
                    that.tianjiazhuomianBtn.active = false
                },
            });
        } else {
            this.tianjiazhuomianBtn.active = false
        }


        if(window['qg']){
            this.moreGameBtn.active = true
            let taht = this
            window['qg'].hasShortcutInstalled({
                success: function(status) {
                  if(status) {
                    console.log('已创建')
                    taht.tianjiazhuomianBtn.active = false
                  }else{
                    console.log('未创建')
                    taht.tianjiazhuomianBtn.active = true
                  }
                }
              })
            this.yinsiBtn.active = true
        }else{
            this.tianjiazhuomianBtn.active = false
        }
    }

    tianjiadaozhuomian() {
        if (window['tt']) {
            let that = this
            window['tt'].addShortcut({
                success() {
                    cc.log("添加桌面成功");
                    that.tianjiazhuomianBtn.active = false
                    sers().uiSrv.showMessage("添加桌面成功");
                },
                fail(err) {
                    cc.log("添加桌面失败", err.errMsg);
                    sers().uiSrv.showMessage("添加桌面失败");

                },
            });
        }else if(window['qg']){
            let that = this
            window['qg'].installShortcut({
                success: function() {
                  console.log('创建成功')
                  that.tianjiazhuomianBtn.active = false
                }
              })
        }
    }

    vMoreGame(){
        var boxBannerAd = null
        if (window['qg'].createBoxBannerAd) {
            boxBannerAd = window['qg'].createBoxBannerAd({
                posId: '044f5af0ad4345d88e36353325db720f'
            })
            boxBannerAd.onError(function (err) { console.log("盒子横幅广告加载失败", err) })
            // 广告数据加载成功后展示
            boxBannerAd.show().then(function () { console.log('show success') })
        } else {
            console.log('暂不支持互推盒子相关 API')
        }
    }

    showYinsi(){
        sers().uiSrv.showYinsiPage();
    }
    @property(cc.Label)
    danguanjiesuo : cc.Label = null


    public unlockNumber = 1
    public muqianguankancishu = 0

    public muqianItem:gameItem = null

    private unlockData = null
    private lockLevel(data) {
        cc.log(data)
        this.unlockData = data
        this.cut.string = UserService.unlockCnt + '/3'
        this.unlockNumber = data.unlockNumber
        this.muqianguankancishu = data.muqianguankancishu
        this.muqianItem = data.muqianItem
        if(data.unlockNumber>1){
            this.danguanjiesuo.string = this.muqianguankancishu + '/'+this.unlockNumber
            this.danguanjiesuo.node.active = true
        }else{
            this.danguanjiesuo.node.active = false
        }
        UIService.openPageBasicAni2(this.jiesuoNode, true)
    }


    shangyiye() {
        mgrs().soundMgr.playBtnSound();
        let z = this.pageView.getCurrentPageIndex()
        this.pageView.setCurrentPageIndex(z - 1)
        this.updatav()
        sers().platformSrv.platformApi.FullScreenVideoAd()

    }

    xiayiye() {
        mgrs().soundMgr.playBtnSound();
        let z = this.pageView.getCurrentPageIndex()
        this.pageView.setCurrentPageIndex(z + 1)
        this.updatav()
        sers().platformSrv.platformApi.FullScreenVideoAd()

    }

    updatav() {
        this.yeshu.string = this.pageView.getCurrentPageIndex() + 1 + '/' + this.pageView.getPages().length;

        this.shang.interactable = true
        this.xia.interactable = true
        if (this.pageView.getCurrentPageIndex() <= 0) {
            this.shang.interactable = false
        }
        if (this.pageView.getCurrentPageIndex() == this.pageView.getPages().length - 1) {
            this.xia.interactable = false
        }
    }

    OnBtnTest() {
        mgrs().gameMgr.backHomePage();
    }


    jiesuo() {
        mgrs().soundMgr.playBtnSound();
        let data = sers().userSrv.getGameLevelData()
        let unlockLevel = this.unlockData.level
        let gameid = this.unlockData.gameId
        let stage_name =  this.unlockData.title
        let datas = {
            stage_type: '' + gameid,
            stage_id: '' + unlockLevel,
            event: "jiesuo",
            stage_name: stage_name
        }
        sers().platformSrv.platformApi.loadAndShowVideoAd(() => {
            this.muqianguankancishu++
            this.muqianItem.getComponent(gameItem).muqianguankancishu = this.muqianguankancishu
            if(this.danguanjiesuo.node.active && this.muqianguankancishu<this.unlockNumber){
                this.danguanjiesuo.string = this.muqianguankancishu + '/'+this.unlockNumber
            }else{
                data.lock.push({
                    level: +unlockLevel,
                    gameId: gameid
                })
                sers().userSrv.setGameLevelData(data)
                EventManager.emit(EventType.DirectorEvent.updataLevelList);
                UIService.closePageBasicAni2(this.jiesuoNode, true, true)
            }
            

            sers().platformSrv.platformApi.reportAnalytics('stage_watch_video', datas)
        }, (err) => {

        }, null, "解锁关卡");
    }

    @property(cc.Label)
    cut: cc.Label = null

    quanbujiesuo() {
        mgrs().soundMgr.playBtnSound();
        let isInfinityPowerModel = Number(sers().localStorageSrv.get(UserService.infinityPowerModel)) != 0;
        if (isInfinityPowerModel) {
            //XXX 
            // sers().uiSrv.showMessage("已经开启无限体力模式！");
            EventManager.emit(EventType.DirectorEvent.updataLevelList);
            UIService.closePageBasicAni2(this.jiesuoNode, true, true)
        } else {
            sers().platformSrv.platformApi.loadAndShowVideoAd(() => {
                UserService.unlockCnt++;
                this.cut.string = UserService.unlockCnt + '/3'
                if (UserService.unlockCnt >= 3) {
                    // sers().userSrv.addPower(999);
                    sers().localStorageSrv.set(UserService.infinityPowerModel, 1);
                    sers().localStorageSrv.set(UserService.infinityPowerDate, Date.now());
                    EventManager.emit(EventType.DirectorEvent.updataLevelList);
                    UIService.closePageBasicAni2(this.jiesuoNode, true, true)
                }

                let datas = {
                    event: '解锁全部关卡'
                }
                sers().platformSrv.platformApi.reportAnalytics('common_video', datas)

            }, () => {

            }, null, "解锁全部关卡");
        }
    }

    No() {
        mgrs().soundMgr.playBtnSound();
        UIService.closePageBasicAni2(this.jiesuoNode, true, true)
    }

    setBtn() {
        mgrs().soundMgr.playBtnSound();
        sers().uiSrv.showSettingPage();
    }

    huadong() {
        this.updatav()
    }

    
    
    // update (dt) {}
}
